package com.webchat.chat.service.impl;

import com.corundumstudio.socketio.BroadcastOperations;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.SocketIOServer;
import com.webchat.chat.core.dto.evenMessage.MsgInfo;
import com.webchat.chat.core.enums.MsgType;
import com.webchat.chat.core.redis.RedisService;
import com.webchat.chat.core.tools.RedisConstant;
import com.webchat.chat.core.tools.SocketConstant;
import com.webchat.chat.dao.ChatRecordMapper;
import com.webchat.chat.model.ChatRecord;
import com.webchat.chat.service.ChatRecordService;
import com.webchat.chat.core.AbstractService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.Date;
import java.util.List;


/**
 * Created by admin on 2018-06-29.
 */
@Service
@Transactional
public class ChatRecordServiceImpl extends AbstractService<ChatRecord> implements ChatRecordService {
    @Resource
    private ChatRecordMapper chatRecordMapper;
    @Resource
    private SocketIOServer socketIOServer;
    @Resource
    private RedisService redisService;


    @Override
    public List<ChatRecord> findNeedAuditMessageByTenantCode(String tenantCode) {
        return chatRecordMapper.findNeedAuditMessageByTenantCode(tenantCode);
    }

    @Override
    public List<ChatRecord> findChatRecordByInfo(ChatRecord chatRecord) {
        return chatRecordMapper.findChatRecordByInfo(chatRecord);
    }

    @Override
    public List<ChatRecord> findByRoomId(String roomId, Date endTime) {
        return chatRecordMapper.findByRoomId(roomId, endTime);
    }



    @Override
    public Boolean messageAudit(String chatRecordIds) {
        List<ChatRecord> chatRecords = chatRecordMapper.selectByIds(chatRecordIds);
        chatRecords.forEach( e -> {
            if (e.getAuditStatus()){
                String roomId = e.getRoomId();
                BroadcastOperations roomOperations = socketIOServer.getRoomOperations(roomId);
                if (roomOperations == null) {
                    return;
                }
                MsgInfo msg = e.getMsg();
                msg.setMsgType(MsgType.审核通过消息);
                roomOperations.sendEvent(SocketConstant.CS_CHAT_C, msg);
                e.setMsg(msg);
                e.setAuditStatus(false);
                chatRecordMapper.updateByPrimaryKey(e);
            }
        });
        return true;
    }


}
